<script setup>
import Header from './components/Header.vue'
import { useRoute, useRouter } from 'vue-router'
import { onMounted , ref, watch, } from 'vue'
import { getDetailBook, subBook, getChapterList, rateBook } from '@/api/book/index.js'
import { message } from 'ant-design-vue';
import { payAuthor } from '@/api/user/index.js'
import { useUserStore } from '@/store/modules/user.js'
import { getBookCommentsList, publishComment, delCommentOne, isLike } from '@/api/comment/index.js'
const userStore = useUserStore()
// 书籍状态
const bookStatus = [
  { color: 'processing', text: '连载中' }, 
  { color: 'success', text: '已完结' }, 
  { color: 'warning', text: '审核中' }, 
  { color: 'error', text: '审核失败' }
]
const { params } = useRoute()
const router = useRouter()
const activeKey = ref('info')
const status = ref()
const sort = ref(0)
const firstChapter = ref()
const isPay = ref(false)
const amount = ref(0)
const bookInfo = ref({
})
const chapterList = ref()
onMounted(() => {
  loadData(params)
  getChapterList({ sort: 0, ...params })
    .then(res => {
      firstChapter.value = res[0]
      chapterList.value = res
    })
})

// 监听sort变化前端处理排序
watch(sort, () => {
  chapterList.value.reverse()
})

const handleReade = (id) => {
  router.push(`/shuku/${params.id}/${id}`)
}

const readNow = () => {
  if (bookInfo.value.recentChapterId) {
    return  router.push(`/shuku/${params.id}/${bookInfo.value.recentChapterId}`)
  }
  router.push(`/shuku/${params.id}/${firstChapter.value.id}`)
}
const handleSub = () => {
  subBook(params)
    .then(() => {
      message.success('添加成功')
      loadData(params)
    })
    .catch((err) => {
      message.success(err || '请先登录')
    })
}
const loadData = params => {
  getDetailBook(params)
  .then(res => {
    bookInfo.value = res
    status.value = bookStatus[res.status]
  })
  getCommentList()
}
// 打赏
const handleIsPay = () => {
  if (!userStore.userInfo.id) return message.error('请先登录')
  if (isPay.value) {
    if (amount.value <= 0) return message.error('请输入正确的金额')
    payAuthor({ novelId: params.id, amount: amount.value, authorId: bookInfo.value.authorId})
      .then(() => {
        message.success('打赏成功')
        isPay.value = false
        amount.value = 0
      })
      .catch((err) => {
        message.error(err || '打赏失败')
        amount.value = 0
      })
      .finally(() => {
        isPay.value = false
        amount.value = 0
      })
  } else {
    isPay.value = true
  }
}
// 取消
const cancel = () => {
  isPay.value = false
  amount.value = 0 
}

// 评书
const rate = ref(0)
const desc = ref(['不堪入目', '令人心酸', '平凡无奇', '脍炙人口', '好评如潮', '神作'])
const onChange = score => {
  if (!userStore.userInfo.id) return message.error('请先登录')
  rateBook({  id: params.id ,score })
    .then(() => {
      message.success('评分成功')
      loadData(params)
      rate.value = 0
    })
    .catch(err => {
      message.error(err || '评分失败')
      rate.value = 0
    })
}
// 评论
const comment = ref('')
const submitting = ref(false)
const commentsList = ref([])

// 发表评论
const handleSubmit = () => {
  if (!userStore.userInfo.id) return message.error('请先登录')
  const data = {
    novelId: params.id,
    commentType: 0,
    commentReplyUserName: null,
    commentReplyUserId: null,
    commentReplyId: null,
    commentParentId: 0,
    commentContent: comment.value
  }
  submitting.value = true
  publishComment(data).then(() => {
    message.success('评论成功')
    getCommentList()
    comment.value = ''
    submitting.value = false
  }).catch(err => {
    message.error(err || '评论失败')
    submitting.value = false
  })
}

//获取评论列表
const getCommentList = () => {
  const data = {
    novelId: params.id,
    pageNum: 1,
    pageSize: 100
  }
  getBookCommentsList(data).then(res => {
    commentsList.value = res?.records
  })
}

// 点赞
const handleThumb = (like, commentId) => {
  if (!userStore.userInfo.id) return message.error('请先登录')
  const data = {
    novelId: params.id,
    commentId,
    type: 0
  }
  data.type = like ? 1 : 0
  isLike(data).then(() => {
    if (data.type) {
      message.success('取消成功')
    } else {
      message.success('点赞成功')
    }
    getCommentList()
  }).catch(err => {
    message.error(err || '失败')
  })
}

// 删除评论
const delComment = (id) => {
  delCommentOne({ id }).then(() => {
    message.success('删除成功')
    getCommentList()
  }).catch(err => {
    message.error(err || '删除失败')
  })
}
</script>
<template>
  <Header />
  <div class="main">
    <div class="main-con">
      <div class="wra-book">
        <div class="cover">
          <img :src="bookInfo.cover" alt="">
        </div>
        <div class="desc">
          <h2 class="title">{{ bookInfo.title }}</h2>
          <div class="status">
            <a-tag :color="status?.color">{{ status?.text }}</a-tag>
          </div>
          <div class="author">作者: <span>{{ bookInfo.authorName }}</span> </div>
          <div class="wra-info">
            <div class="count">字数: <span> {{ bookInfo.wordNums }} </span></div>
            <div class="pv">阅读数: <span> {{ bookInfo.browseNums }} </span></div>
            <div class="hot">订阅数：<span>{{ bookInfo.subscribeNums }}</span></div>
          </div>
          <div class="btn-war">
            <a-button class="btn" type="primary" shape="round" @click="readNow">开始阅读</a-button>
            <a-button type="primary" shape="round" ghost @click="handleSub" :disabled="bookInfo.existBookSelf">{{ bookInfo.existBookSelf ? '已在书架' : '加入书架'}}</a-button>
          </div>
        </div>
        <div class="score">
            <div class="pay">
              <a-input-number style="border-radius: 20px; width: 140px;" v-if="isPay" v-model:value="amount"></a-input-number>
              <a-button type="primary" shape="round" style="margin-left: 10px;" @click="handleIsPay">{{ isPay ? '确认打赏' : '打赏' }}</a-button>
              <a-button type="link"  style="margin-left: 10px;" v-if="isPay" @click="cancel">取消打赏</a-button>
            </div>
            <div class="score-info">
             <span>本书的综合评分：</span> <a-rate v-model:value="bookInfo.score" v-if="bookInfo.score" disabled :tooltips="desc"/> <span v-if="!bookInfo.score">暂无评分</span> 
            </div>
            <div class="score-info">
             <span>你对本书的评价：</span> 
             <a-rate v-model:value="bookInfo.scoreSelf" v-if="bookInfo.scoreSelf && userStore.userInfo.id" :tooltips="desc" disabled/>
             <a-rate v-model:value="rate" @change="onChange" v-if="!bookInfo.scoreSelf" :tooltips="desc"/>
            </div>
        </div>
      </div>
    </div>
    <div class="aside">
      <div class="extra">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="info" tab="作品介绍">
            <div class="desc">简介</div>
            <p>{{ bookInfo.introduction }}</p>
          </a-tab-pane>
          <a-tab-pane key="chapter" tab="章节目录" forceRender>
            <div class="title">
              <span class="count">共{{ chapterList?.length }}章</span>
              <a-radio-group v-model:value="sort" button-style="solid">
                <a-radio-button :value="0">升序</a-radio-button>
                <a-radio-button :value="1">降序</a-radio-button>
              </a-radio-group>
            </div>
            <div class="cha-con">
              <span @click="() => handleReade(cha.id)" v-for="cha in chapterList" :key="cha.id">{{ `第${cha.chapterNo}章${cha.chapterName}` }}</span>
            </div>
          </a-tab-pane>
          <a-tab-pane key="comment" tab="作品评论">
            <div class="my-comment">
              <a-comment>
                <template #avatar>
                  <a-avatar :src="userStore.userInfo.avatar" alt="avatar" />
                </template>
                <template #content>
                  <a-form-item>
                    <a-textarea v-model:value="comment" :rows="4" />
                  </a-form-item>
                  <a-form-item>
                    <a-button html-type="submit" :loading="submitting" type="primary" @click="handleSubmit">
                      发表评论
                    </a-button>
                  </a-form-item>
                </template>
              </a-comment>
            </div>
            <div class="comment-list">
              <div class="box" v-for="comment in commentsList" :key="comment.id">
                <div class="header">
                  <div class="title">{{ comment.commentUserName }}</div>
                  <div class="unit">{{ `${comment.diff}${comment.diffUnit}前` }}</div>
                </div>
                <div class="con">{{ comment.commentContent }}</div>
                <div class="action">
                  <div class="up"><a-button type="link"  @click="() => handleThumb(comment.alreadySupport, comment.id)"> <span>{{  comment.commentNums || ' ' }}</span>{{ comment.alreadySupport ? '取消' : '点赞' }}</a-button></div>
                  <div class="del"><a-button type="link" v-if="userStore.userInfo.id === comment.commentUserId" @click="() => delComment(comment.id)">删除</a-button></div>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>      
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
body {
  margin: 0;
  padding: 0;
}
.main {
  .comment-list {
    width: 900px;
    padding-left: 44px;
    border-radius: 4px;
    .header {
      display: flex;
      justify-content: space-between;
      .title {
        font-weight: 500;
        font-size: 15px;
        color: #252933;
        max-width: 90px;
        line-height: 26px;
      }
    }
    .con {
      margin-top: 8px;
      padding: 16px;
    }
    .action {
      display: flex;
      .del {
        margin-left: 16px;
      }
    }
  }
  .box {
    background: rgba(247,248,250,.7);
    padding: 16px;
    border-bottom: 1px solid #eee;
}

  .main-con {
    background-color: rgb(248,248,248);
    .desc {
      font-size: 16px;
      color: #222;
    }
    .title {
      font-weight: 600;
    }
    .btn-war {
      .btn {
        margin-right: 10px;
      }
    }
  }
  .aside {
    padding: 20px 30px;
    margin: 0 auto;
    width: 960px;
  }
  .wra-book {
    padding: 40px 30px;
    margin: 0 auto;
    width: 960px;
    height: 377px;
    display: flex;
    .score {
      flex: 1;
      text-align: right;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .score-info {
        padding-right: 15px;
        margin-top: 30px;
        span {
          font-size: 18px;
          font-weight: 600;
        }
      }
    }
    .cover {
      margin-right: 40px;
    }
    .desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 280px;
    }
    .cover img{
      width: 210px;
      height: 280px;
    }
  }
  .extra {
    margin-top: 60px;
    .desc {
      font-size: 20px;
      line-height: 28px;
      font-weight: 700;
      margin-bottom: 10px;
    }
    .title {
      display: flex;
      justify-content: space-between;
      .count {
        font-size: 20px;
        font-weight: 700;
        color: #222;       
      }

    }
    .cha-con {
      padding: 20px 0;
      display: flex;
      color: #222;  
      span {
        width: 450px;
        font-size: 16px;
        line-height: 48px;
        height: 48px;
        cursor: pointer;
        &:hover {
          color: #b04f08;
        };
      }
      flex-wrap: wrap;
    }

  }
}
</style>